<template>
  <div :id="id" ref="chart" :style="{ width: width, height: height }"></div>
</template>

<script>
import echarts from 'echarts'
import { parseTime, chunk } from '@/utils'
import { sensorStation } from '@/api/api'

export default {
  props: {
    id: {
      type: String,
      default: ''
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '550px'
    },
    series: {
      type: Array,
      default: null
    },
    minute: {
      type: Number,
      default: 1 // 1, 5, 30, 60, 1440
    },
    companyArr: {
      type: Array,
      default: null
    }
  },
  data() {
    return {
      myChart:undefined,
      legend: [],
      device: []
    }
  },
  watch: {
    minute: function (oldValue, newValue) {
      if (oldValue !== newValue) {
        if (this.series.length) {
          this.timeInterval()
        }
      }
    },
    series: function (oldValue, newValue) {
      if (oldValue !== newValue) {
        if (this.series.length) {
          this.deviceInterval()
        }
      }
    },
   companyArr: function (oldValue, newValue) {
      this.deviceInterval()
    }
  },
  mounted() {
      let that = this
      // 基于准备好的dom，初始化echarts实例
      let bar_dv = this.$refs.chart
      if(that.myChart===undefined){
        that.myChart = echarts.init(bar_dv)
      } else{
        that.myChart.clear()
      }
       that.myChart.showLoading({
            text: '数据正在努力加载...',
            textStyle: { fontSize : 30 , color: '#444' },
            effectOption: {backgroundColor: 'rgba(0, 0, 0, 0)'}
        })

  },
  methods: {
    async deviceInterval() {
      sensorStation('post', { pageIndex: 1, pageSize: 1e4, orderBy: 'createdTime', orderByAscent: false }, false).then(async (res) => {
        this.setDevice(res.data.items).then((data) => {
          this.timeInterval().then((response) => {
            this.ShowmyChart(response)
          })
        })
      })
    },
    setDevice(list) {
      return new Promise((resolve, reject) => {
        list.forEach((item, index) => {
          // 设备data
          this.device[index] = []
          this.series.forEach(dID => {
            if (dID.deviceID === item.code) {
              this.device[index].push(dID)
            }
          })
        })
        resolve()
      })
    },
    timeInterval() {
      return new Promise((resolve, reject) => {
        if (this.minute === 1) {
          resolve(this.series)
          // this.ShowmyChart(this.series)
        } else {
          let series = []
          this.device.forEach(die => {
            // 平均等分
            let ary = chunk(die, this.minute)
            let evenly = ary.map(minute => {
              let total = minute[0]
              // 平均值
              this.legend.forEach(item => {
                total[item] = (
                  minute
                    .map(node => {
                      return Number(node[item])
                    })
                    .reduce((acc, cur) => {
                      return acc + cur
                    }) / minute.length
                ).toFixed(2)
              })
              return total
            })
            series = [...series, ...evenly]
          })
          resolve(series)
          // this.ShowmyChart(series)
        }
      })
    },
    ShowmyChart(series) {
        let that=this
        let seris= that.companyArr.map(item => {
          return {
            type: 'line',
            name: item.label,
            data: series
              .filter(r => r.label == item.label)
              .map(node => {
                return Number(node.trackingValue)
              })
          }
        })
        if(seris.length==0){
          return
        }
      //let myChart = echarts.init(document.getElementById(this.id))
      // 绘制图表
      that.myChart.setOption({
        tooltip: {
          trigger: 'axis',
          formatter: datas => {
            let val = {}
            let res = datas[0].name + '<br/>'
            datas.forEach((item, index) => {
              res += item.marker + datas[index].seriesName + '：' + item.value + '<br/>'
            })
            return res
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        toolbox: {
          feature: {
            // saveAsImage: {}
          }
        },
        yAxis: {
          type: 'value'
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: series.map(item => {
            return parseTime(new Date(item.logTime).getTime())
          })
        },
        legend: {
          left: '33%',
          data: that.companyArr.map(item => {
            return item.label
          })
        },
        series:seris
      })

       that.myChart.hideLoading()
    }
  }
}
</script>
